﻿using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using Framework.Manager;
using Newtonsoft.Json;

namespace Framework.Data.Config
{
    public class ConfigContainer<T> : IConfigContainer where T : ConfigBase
    {
        private bool mIsDeserialize = false;
        private List<T> mConfigList = new List<T>();
        private Dictionary<string, T> mConfigDictionary = new Dictionary<string, T>();

        public void DeserializeConfig()
        {
            if (!mIsDeserialize)
            {
                string configName = typeof(T).Name;
                TextAsset textAsset = ManagerCollection.ResourceManager.GetTextAsset(configName);
                if (textAsset != null)
                {
                    mConfigList = JsonConvert.DeserializeObject<List<T>>(textAsset.text);
                    for (int i = 0; i < mConfigList.Count; i++)
                    {
                        T config = mConfigList[i];
                        mConfigDictionary.Add(config.id, config);
                    }
                    mIsDeserialize = true;
                }
            }
        }

        public async Task DeserializeConfigAsync()
        {
            if (!mIsDeserialize)
            {
                string configName = typeof(T).Name;
                bool result = await ManagerCollection.LoadManager.LoadAssetAsync(configName);
                if (result)
                    DeserializeConfig();
            }
        }

        public C GetConfig<C>(string pKey) where C : ConfigBase
        {
            T configBase = default;
            mConfigDictionary.TryGetValue(pKey, out configBase);
            return configBase as C;
        }

        public C GetConfig<C>(int pIndex) where C : ConfigBase
        {
            T configBase = default;
            if (pIndex >= 0 && pIndex < mConfigList.Count)
                configBase = mConfigList[pIndex];

            return configBase as C;
        }

        public IConfigBase GetConfig(string pKey)
        {
            T configBase = default;
            mConfigDictionary.TryGetValue(pKey, out configBase);
            return configBase;
        }

        public IConfigBase GetConfig(int pIndex)
        {
            T configBase = default;
            if (pIndex >= 0 && pIndex < mConfigList.Count)
                configBase = mConfigList[pIndex];

            return configBase;
        }
    }
}